#coding:UTF-8

from flask import Flask, request,make_response
from datetime import datetime
from jinja2 import Environment, PackageLoader
import pdfkit, json, time, os, imgkit
from PIL import Image

app = Flask(__name__)

def getHtmlHeight(inputPath):
    imgFileName = str(time.time() * 1000) + ".jpg"
    imgFilePath = "./%s" % imgFileName

    imgkit.from_file(inputPath, imgFilePath)
    img = Image.open(imgFilePath)
    height = img.size[1]
    img.close()
    os.remove(imgFilePath)

    return height


def buildReportPdf(htmlHeight, inputPath, outputPath, isMbti):
    if isMbti:
        options = {'page-size': 'A4', 'margin-top': '0px', 'margin-right': '0px', 'no-outline': None,
                   'margin-bottom': '0px', 'margin-left': '0px'}
    else:
        options = {'page-height':str(htmlHeight * 0.83)+'px', 'page-width': '796px', 'margin-top': '0px', 'margin-right': '0px', 'no-outline': None,
                   'margin-bottom': '0px', 'margin-left': '0px'}
    pdfkit.from_file(inputPath, outputPath, options=options)


def buildReportHtml(data, outputPath):
    env = Environment(loader=PackageLoader("templates"),
                      extensions=['jinja2.ext.do', 'jinja2.ext.loopcontrols'])

    env.filters['dateformat'] = dateformat
    env.filters['findSubStr'] = findSubStr
    env.filters['splitStr'] = splitStr

    template = env.get_template("report-template.html")

    mbtiData = readJsonFromFile("static/json/mbti-data.json")
    jobsData = readJsonFromFile("static/json/jobs.json")
    enneagramData = readJsonFromFile("static/json/enneagram.json")

    html_content = template.render(report=data, mbtiData=mbtiData, jobsData=jobsData, enneagramData=enneagramData)
    writeJsonToFile(html_content, outputPath)


def writeJsonToFile(content, path):
    with open(path, 'w', encoding="utf-8") as file:
        file.write(content)


def readJsonFromFile(path):
    with open(path, encoding="utf-8") as load_f:
        return json.load(load_f)


def dateformat (value, format="%Y-%m-%d"):
    return datetime.fromtimestamp(value / 1000 + 28800).strftime(format)


def findSubStr (str, subStr):
    return str.find(subStr)

def splitStr (str, separator):
    return str.split(separator, -1)


def isMbti (data):
    reportDict = json.loads(str(data, encoding="utf-8"))
    if 55327 == reportDict["composerTemplateId"] or 51847 == reportDict["composerTemplateId"]:
        return True
    else:
        return False

@app.route('/report-pdf/', methods=['POST'])
def getReportPdf():
    data = request.data
    if data:
        try:
            htmlFileName = str(time.time() * 1000) + ".html"
            htmlFilePath = "./%s" % htmlFileName
            buildReportHtml(json.loads(str(data, encoding="utf-8")), htmlFilePath)

            pdfFileName = str(time.time() * 1000) + ".pdf"
            pdfFilePath = "./%s" % pdfFileName

            htmlHeight = getHtmlHeight(htmlFilePath)

            buildReportPdf(htmlHeight, htmlFilePath, pdfFilePath,isMbti(data))

            with open(pdfFilePath, 'rb') as load_f:
                data = load_f.read()
                response = make_response(data)
                response.status_code = 200
        except Exception as e:
            print(e)
            response = make_response("下载失败");
            response.status_code = 500
        finally:
            # 删除临时文件
            os.remove(htmlFilePath)
            os.remove(pdfFilePath)
        return response
    else:
        pass
    response = make_response("下载失败");
    response.status_code = 500
    return response


if __name__ == '__main__':
    app.run()


